<?php
include_once "baseChannel.php";
date_default_timezone_set('Asia/Chongqing');
class chengyu extends baseChannel
{
    public $appid;
    public $apikey;

    public function __construct($setting)
    {
        parent::__construct($setting);
        $this->appid = $setting['appid'];
        $this->apikey = $setting['apikey'];
    }
    /*通用签名方法*/
    public function getSign($params)
    {
        unset($params['sign']);
        ksort($params);
        $params['appsecret'] = $this->apikey;
        $str = http_build_query($params);
        $str = urldecode($str);
        $md5 = strtoupper(md5($str));
        return $md5;
    }
    /*查询余额*/
    public function queryBalance($params = [])
    {
        $url = $this->api_url . '/api/interface/queryBalance';

        $post_data = [
            'appid' => $this->appid,
            'timestamp' => date('Y-m-d H:i:s')
        ];

        $sign = $this->getSign($post_data);
        $post_data['sign'] = $sign;

        $return_str = $this->httpRequest($url, 'POST', $post_data);
        $return_data = json_decode($return_str, 1);

        if ($return_data['code'] == 200) {
            return [
                'error' => 0,
                'msg' => '查询成功',
                'balance' => $return_data['data']['balance'] ?? 0, //余额
                'credit' => 0, //授信
                'code' => 200
            ];
        }
        return [
            'error' => 1,
            'msg' => $return_data['message'] ?? '查询失败',
            'code' => 500
        ];
    }
    public function getProduct($page = 1)
    {
        $url = $this->api_url . '/api/interface/goodsList';
        $post_data = [
            'appid' => $this->appid,
            'timestamp' => date('Y-m-d H:i:s'),
            'limit' => 200,
            'page' => $page
        ];
        $sign = $this->getSign($post_data);
        $post_data['sign'] = $sign;
        $return_str = $this->httpRequest($url, 'POST', $post_data);
        $return_data = json_decode($return_str, 1);

        return $return_data;
    }
    public function queryProduct($params = [])
    {
        $nums = 0;
        $total = 1;
        $page = 1;
        $product_list = [];
        while ($nums < $total) {
            $product_info = $this->getProduct($page);

            if ($product_info['code'] == 200) {
                $total = $product_info['data']['total'];
                if (count($product_info['data']['list']) > 0) {
                    $product_list = array_merge($product_list, $product_info['data']['list']);
                }
                $nums = $nums + 200;
            } else {
                $nums = $total + 1;
            }
            $page = $page + 1;
        }
        $product_map = [];
        $items = $product_list;
        //        var_dump($items);exit;
        foreach ($items as $item) {
            $channel_api_code = $item['productId'];
            $channel_product_status = 1;
            $channel_product_price = $item['price'];

            $product_map[$channel_api_code] = [
                'channel_id' => $this->channel_id ?? 0,
                'channel_api_code' => $channel_api_code,
                'channel_product_status' => $channel_product_status,
                'channel_product_price' => $channel_product_price,
            ];
        }
        return [
            'error' => 0,
            'msg' => '查询成功',
            'data' => $product_map ?? [], //余额
            'code' => 200
        ];
    }
    public function queryOrder($params)
    {
        $url = $this->api_url . '/api/interface/queryRecharge';

        $post_data = [
            'appid' => $this->appid,
            'timestamp' => date('Y-m-d H:i:s'),
            'orderId' => $params['channel_order_sn']
        ];

        $sign = $this->getSign($post_data);
        $post_data['sign'] = $sign;

        $return_str = $this->httpRequest($url, 'POST', $post_data);
        $return_data = json_decode($return_str, 1);

        $ret = [
            'error' => 0,
            'order_status' => 2,
            'msg' => '初始化',
            'pz' => '', //凭证
            'post_data' => json_encode($post_data), //提交字符串
            'channel_data' => $return_str, //返回字符串
            'code' => 200
        ];
        //成功
        if ($return_data['code'] == 200 && $return_data['data']['orderStatus'] == 1) {
            $ret['order_status'] = self::OrderSuccess;
            $ret['msg'] = '充值完成:' . $return_data['orderStatusText'];
        }

        // 失败
        if ($return_data['code'] == 200 && $return_data['data']['orderStatus'] == -1) {
            $ret['order_status'] = self::OrderFail;
            $ret['msg'] = '充值失败:' . $return_data['orderStatusText'];
        }

        return $ret;
    }
    public function submitOrder($mobile, $code, $params = [])
    {
        $url = $this->api_url . '/api/interface/recharge';

        $post_data = [
            'appid' => $this->appid,
            'timestamp' => date('Y-m-d H:i:s'),
            'mobile' => $mobile,
            'productId' => $code,
            'agentOrderId' => $params['push_order_sn'],
        ];

        $sign = $this->getSign($post_data);
        $post_data['sign'] = $sign;

        $return_str = $this->httpRequest($url, 'POST', $post_data);
        $return_data = json_decode($return_str, 1);

        $ret = [
            'error' => -1,
            'msg' => '初始化',
            'channel_order' => $return_data['data']['orderId'] ?? '',
            'post_data' => json_encode($post_data),
            'channel_data' => $return_str,
            'code' => 200,
            'channel_order_price' => null,
            'channel_balance' => null,
        ];
        if ($return_data['code'] == 200) {
            $ret['error'] = 0;
            $ret['msg'] = $return_data['message'] ?? '下单成功';
        } else {
            if (isset($return_data['code'])) {
                $ret['error'] = 1;
                $ret['code'] = 500;
                $ret['msg'] = $return_data['message'] ?? '下单失败';
            }
        }

        return $ret;
    }


    public function callback($params)
    {
        $this->callback_params = $params;
        $this->channel_order_sn = trim($params['orderId']);
        $this->push_order_sn = $params['agentOrderId'];
        //返回参数
        $res = $this->initCallBackParam();
        //订单状态
        $order_status = $params['orderStatus'];
        $msg = $params['orderStatusText'];
        //凭证
        $pz = '';

        $sign = $this->getSign($params);

        // if($sign != strtoupper($params['sign'])){
        //     $res['error'] = 1;
        //     $res['msg'] = '签名不匹配';
        //     $res['resp_data'] = 'fail';
        //     return $res;
        // }

        if ($order_status == 1) {
            $res['order_status'] = self::OrderSuccess;
            $res['msg'] = $msg ?? '充值完成';
        }

        if ($order_status == -1) {
            $res['order_status'] = self::OrderFail;
            $res['msg'] = $msg ?? '充值失败';
        }
        return $res;
    }
}
